package com.xx.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

import com.xx.entity.Atmessage;
import com.xx.entity.Message;
import com.xx.util.DBHelp;
import com.xx.util.DateUtil;
import com.xx.util.Pager;
import com.xx.util.RowMapper;

public class MessageDao {

	DBHelp<Message> db = new DBHelp<Message>();

	public int getMessageCount(String projectid) {
		String sql = "select count(*) from t_message where t_project_id = ? ";
		return db.executeQueryForCount(sql, projectid);
	}

	public Pager<Message> findMessage(String id, int num) {

		Pager<Message> pager = new Pager<Message>(num, getMessageCount(id));

		String sql = "select id,content,createtime,t_employee_id,t_project_id from t_message where t_project_id=?  ORDER BY createtime DESC  limit ?,?";

		List<Message> messages = db.executeQueryForList(sql,
				new MessageMappe(), id, pager.getStartIndex(),
				pager.getPageSize());

		pager.setResult(messages);

		return pager;

	}

	public void insert(Message message) {
		String sql = "insert into t_message(id,content,createtime,t_employee_id,t_project_id) value(?,?,?,?,?)";
		db.executeSQL(sql, message.getId(), message.getContent(),
				message.getCreatetime(), message.getEmployeeid(),
				message.getProjectid());

	}

	public class MessageMappe implements RowMapper<Message> {

		public Message mapperRow(ResultSet rs) throws SQLException {
			// TODO Auto-generated method stub

			Message message = new Message();
			message.setId(rs.getString("id"));
			message.setContent(rs.getString("content"));
			message.setCreatetime(rs.getString("createtime"));
			message.setEmployeeid(rs.getString("t_employee_id"));
			message.setProjectid(rs.getString("t_project_id"));
			LoginDao lg = new LoginDao();
			message.setEmployee(lg.findObject(rs.getString("t_employee_id")));
			try {
				String state = DateUtil.times(rs.getString("createtime"), lg
						.findObject(rs.getString("t_employee_id"))
						.getUsername());
				message.setState(state);

			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return message;

		}

	}

	public void del(String mid) {
	String sql="delete from t_message where id=?";
	db.executeSQL(sql, mid);
		
	}

	public Message findByid(String mid) {
		String sql = "select id,content,createtime,t_employee_id,t_project_id from t_message where id=?";
		return db.executeQueryForObject(sql, new MessageMappe(), mid);
	}
}
